<script setup lang="tsx">
import BaseInfo from './components/Detail/BaseInfo/index.vue'
import Team from './components/Detail/Team/index.vue'
import Delivery from './components/Detail/Delivery/index.vue'
import Logistics from './components/Detail/Logistics/index.vue'
import FollowList from './components/Detail/FollowList/index.vue'
import ReceiptManagement from './components/Detail/ReceiptManagement/index.vue'
import InvoicingHistory from './components/Detail/InvoicingHistory/index.vue'
import FileCabinet from './components/Detail/FileCabinet/index.vue'
import WorkOrderRecord from './components/Detail/WorkOrderRecord/index.vue'
import ReturnsRefund from './components/Detail/ReturnsRefund/index.vue'
import RelatedProducts from './components/Detail/RelatedProducts/index.vue'
import ApprovalRecord from './components/Detail/ApprovalRecord/index.vue'
import OperateRecord from './components/Detail/OperateRecord/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useEnumeratePicker, encryptParam, decryptParam } from '@/utils'
import {
  getOrderEnumApi,
  getDetailApi,
  contractPreviewApi,
  orderSurePaymentApi,
  orderCancelApi,
  orderDeleteApi,
  lockInventoryApi,
  orderCancelUpdateApi
} from '@/api/order'
import DialogUpload from '@/components/OrderPayment/UploadPayment/index.vue'
import DialogPartShop from './components/DialogPartShop/index.vue'
const { push, go } = useRouter()
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
const { query } = useRoute()
const route = useRoute()
const { t } = useI18n()

const isLoading = ref(true) // 设置加载状态
const currentRow = ref<Record<string, any>>({})

const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()

// 跳转编辑
const action = () => {
  push({
    path: `/order/order-management/edit`,
    query: { id: currentRow.value.id }
  })
}
//返回
const back = () => {
  push('/order/order-management')
}

const activeName = ref(getInitialTab())

function getInitialTab(): string {
  // 优先从 URL 参数获取
  if (query.tab) {
    return query.tab as string
  }
  if (query.source) {
    return decodeURIComponent(query.source as string)
  }
  // 从 localStorage 获取上次选中的 tab
  const savedTab = localStorage.getItem('orderDetailActiveTab')
  if (savedTab) {
    return savedTab
  }
  // 默认选中第一个 tab
  return 'base_info'
}

// 监听 activeName 变化，更新 URL 和 localStorage
watch(activeName, (newValue) => {
  console.log('Tab changed to:', newValue)
  const currentQuery = { ...route.query, tab: newValue }
  push({ query: currentQuery })
  localStorage.setItem('orderDetailActiveTab', newValue)
})

// 根据 activeName 动态选择渲染的组件
const currentTabComponent = computed(() => {
  switch (activeName.value) {
    case 'base_info':
      return BaseInfo // 需要先定义 BaseInfo 组件
    case 'team':
      return Team // 需要先定义 Team 组件
    case 'delivery':
      return Delivery // 需要先定义 收货信息 组件
    case 'logistics':
      return Logistics // 需要先定义 物流信息 组件
    case 'follow_list':
      return FollowList // 需要先定义 跟进记录 组件
    case 'work_order_record':
      return WorkOrderRecord // 需要先定义 工单记录 组件
    case 'receipt_management':
      return ReceiptManagement // 需要先定义 回款管理 组件
    case 'invoicing_history':
      return InvoicingHistory // 需要先定义 开票历史 组件
    case 'returns_refund':
      return ReturnsRefund // 需要先定义 关联采购订单 组件
    case 'file_cabinet':
      return FileCabinet // 需要先定义 文件柜 组件
    case 'approval_record':
      return ApprovalRecord // 需要先定义 审批记录 组件
    case 'operate_record':
      return OperateRecord // 需要先定义 操作记录 组件
    case 'related_products':
      return RelatedProducts // 需要先定义 关联产品 组件
    default:
      return BaseInfo // 默认渲染 BaseInfo 组件
  }
})

interface Option {
  label: string
  value: string
}

const options = ref<Option[]>([{ label: t('order.previewContract'), value: 'preview' }]) // 定义为数组类型

// 处理下拉菜单的操作
const handleCommand = (command) => {
  console.log('执行的操作：', command)
  switch (command) {
    case 'newInvoice':
      push(
        `/order/invoice-management/add?order_id=${routerParams.value.id}&order_no=${currentRow?.value?.order_no}&customer_id=${currentRow?.value?.user_id}&cusname=${currentRow?.value?.user_name}&order_type=order`
      )
      break
    case 'orderReturn':
      push(
        `/orderReturn-management/orderReturn/add?order_id=${currentRow.value.id}&order_no=${encodeURIComponent(currentRow.value.order_no)}&customer_id=${currentRow.value.user_id}&cusname=${encodeURIComponent(currentRow?.value?.user_name)}`
      )
      break
    case 'preview':
      getFileUrl()
      break
    case 'copyOrder':
      const encryptedOrderId = encryptParam(currentRow.value.id)
      push({
        path: '/order/order-management/add',
        query: { order: encryptedOrderId }
      })
      break
  }
}
const getFileUrl = async () => {
  try {
    let params = {
      order_id: Number(currentRow.value.id),
      order_type: 'order'
    }
    let response = await contractPreviewApi(params)
    if (response.data.url) {
      pdfUrl.value = response.data.url
      previewVisible.value = true
    }
  } catch (error) {}
}
//获取枚举

const loading = ref<boolean>(false)
const routerParams = ref<Record<string, any>>({})

const form = ref<Record<string, any>>({})
const optionSet = ref<Record<string, any>>({})

const shopTableList = ref<Array<Record<string, any>>>([])
const payTableList = ref<Array<Record<string, any>>>([])
const selfPickupTableList = ref<Array<Record<string, any>>>([])
const receivingTableList = ref<Array<Record<string, any>>>([])
const logisticsTableList = ref<Array<Record<string, any>>>([])
const timeLineList = ref<Array<Record<string, any>>>([])

const receiptMethodList = ref<Array<Record<string, any>>>([])
const orderStatusList = ref<Array<Record<string, any>>>([])
const paymentStatusList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const contractTypeList = ref<Array<Record<string, any>>>([])
const singleOrderMethodList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])

const brandList = ref<Array<Record<string, any>>>([])
const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])

const paymentMethodList = ref<Array<Record<string, any>>>([])
const agingList = ref<Array<Record<string, any>>>([])
const logisticsCompanyList = ref<Array<Record<string, any>>>([])
const itemPayStatusList = ref<Array<Record<string, any>>>([])
const afterSalesStatusList = ref<Array<Record<string, any>>>([])

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getOrderEnumApi({ field: 'all' })
  optionSet.value = resp.data
  receiptMethodList.value = resp.data.delivery_method
  orderStatusList.value = resp.data.status
  contractTypeList.value = resp.data.contract_type
  singleOrderMethodList.value = resp.data.single_order_method
  currencyList.value = resp.data.currency
  paymentStatusList.value = resp.data.pay_status
  paymentMethodList.value = resp.data.pay_method
  brandList.value = resp.data.brand
  warehouseList.value = resp.data.warehouse
  warehouseTypeList.value = resp.data.is_futures
  agingList.value = resp.data.prescription
  logisticsCompanyList.value = resp.data.logistics_company
  itemPayStatusList.value = resp.data.item_pay_status
  operatorList.value = resp.data.operator
  afterSalesStatusList.value = resp.data.aftersales_status || []
}

const initialize = async () => {
  const resp = await getDetailApi(query.id as string)
  form.value = resp.data
  form.value.id = query.id
  currentRow.value = Object.assign({}, resp.data, { id: query.id as string })
  shopTableList.value = resp.data.list
  payTableList.value = resp.data.payment
  selfPickupTableList.value = resp.data.pickup
  receivingTableList.value = resp.data.delivery
  logisticsTableList.value = resp.data.logistics
  timeLineList.value = resp.data.logger
  if ((form.value.pay_status === 3 || form.value.pay_status === 4) && form.value.order_type !== 2) {
    options.value.unshift({
      label: t('order.newReturnRefund'),
      value: 'orderReturn'
    })
  }
  if (form.value.order_status === 100 && form.value.pay_status === 3) {
    options.value.unshift({
      label: t('order.newInvoice'),
      value: 'newInvoice'
    })
  }
  if (form.value.order_type == 1) {
    options.value.push({
      label: t('order.copyOrder'),
      value: 'copyOrder'
    })
  }
}
const countKey = ref(1)
const refresh = async () => {
  await initialize()
  countKey.value++
}
onMounted(async () => {
  Promise.all([getDropDownBoxInfo(), initialize()]).then(() => {
    isLoading.value = false // 数据加载完成后更新状态
  })
})
const checkCustomer = () => {
  push({ path: `/customer/customerList/detail`, query: { id: form.value.user_id } })
}

const previewVisible = ref(false)
const pdfUrl = ref('')
// 关闭预览窗口
const handleClosePreview = () => {
  previewVisible.value = false
  pdfUrl.value = ''
  // 预览合同之后,需要更新文件柜
  if (activeName.value === 'file_cabinet') {
    countKey.value++
  }
}
// 上传支付审核
// type: 1 支付审核 2 物流费用调整
const uploadPayment = (row: Record<string, any>, type: number) => {
  nextTick(() => {
    DialogUploadRef.value!.dialogVisible = true
    DialogUploadRef.value?.getBackShow(row, type, 'order')
  })
}

// 按钮方法

//确认已支付
const handleSurePayment = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.confirmPayment'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await orderSurePaymentApi(row.id)
      ElMessage.success(t('common.operateSucMsg'))
      await initialize()
    })
    .catch(() => {})
}

/**
 * 取消订单
 * @param row
 */
const handleCancelOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.cancel'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await orderCancelApi(row.id)
      ElMessage.success(t('common.operateSucMsg'))
      await initialize()
    })
    .catch(() => {})
}
/**
 * 删除订单
 * @param row
 */
const handleDeleteOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.delete'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await orderDeleteApi(row.id)
      ElMessage.success(t('common.operateSucMsg'))
      push('/order/order-management')
    })
    .catch(() => {})
}
//跳转
const handleJump = (type: string, row: Record<string, any>) => {
  const path = ref<string>('') // 默认值为空字符串
  const query = reactive<{ [key: string]: string }>({}) // 默认值为空字符串
  switch (type) {
    case 'customer':
      path.value = `/customer/customerList/detail`
      query.id = row.user_id
      query.source = `/order/order-management`
      break
    case 'lockInventory':
      handleLockInventory(row)
      break
    case 'auditCancel':
      handleCancelEdit(row)
      break
    default:
      path.value = `/order/order-management/${type}`
      query.id = row.id
      break
  }

  push({ path: path.value, query })
}

//撤销编辑
const handleCancelEdit = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        id: row.id
      }
      let res = await orderCancelUpdateApi(row.id, params)
      console.log('res', res)
      if (res.code === 0) {
        ElMessage.success('撤销成功')
        refresh()
      }
    })
    .catch(() => {})
}
// 打开弹窗
const shopInfo = ref<Record<string, any>>({})
const dialogPartShopRef = ref<InstanceType<typeof DialogPartShop>>()
const dialogKey = ref(0)
const openDeliveryDialog = (row) => {
  shopInfo.value = row
  dialogKey.value++
  nextTick(() => {
    dialogPartShopRef.value!.dialogVisible = true
  })
}
const handleLockInventory = (row: Record<string, any> | undefined) => {
  console.log(row)
  ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await lockInventoryApi({ id: row?.id })
      ElMessage.success(t('common.operateSucMsg'))
      await initialize()
    })
    .catch(() => {})
}
</script>

<template>
  <ContentDetailWrap :title="t('customer.detail')" @back="push('/order/order-management')">
    <template #header v-if="!isLoading">
      <div class="header flex justify-between items-center" :class="{ '!block': isMobile }">
        <div class="header-left flex flex-start items-center">
          <div class="right" :class="{ 'flex justify-between items-center': isMobile }">
            <div class="top">
              <p :style="{ fontWeight: 'bold', color: 'black' }"> {{ form?.order_no }} </p>
            </div>
            <div class="bottom">
              <el-tag
                class="!bg-[var(--el-color-info-light-9)] !border-none !font-600"
                :class="{
                  '!text-[#67c23a]': form?.order_status === 100,
                  '!text-[#c8c9cc]': form?.order_status === 70,
                  '!text-[#20B2AA]': form?.order_status === 50,
                  '!text-[#9370DB]': form?.order_status === 40,
                  '!text-[#1E90FF]': form?.order_status === 30,
                  '!text-[#32CD32]': form?.order_status === 21,
                  '!text-[#FFD700]': form?.order_status === 20,
                  '!text-[#FFA500] ': form?.order_status === 10
                }"
              >
                {{ useEnumeratePicker(orderStatusList, form.order_status) }}
              </el-tag>
              <!-- 售后状态标签 -->
              <el-tag
                v-if="form?.aftersales_status"
                class="!bg-[var(--el-color-info-light-9)] !border-none !font-600 !ml-2"
                :class="{
                  '!text-[#FFA500]': form?.aftersales_status === 1, // 退货中
                  '!text-[#67c23a]': form?.aftersales_status === 4, // 已退货
                  '!text-[#1E90FF]': form?.aftersales_status === 8, // 退款中
                  '!text-[#9370DB]': form?.aftersales_status === 16, // 已退款
                  '!text-[#FF6B6B]': form?.aftersales_status === 32 // 已退货 已退款
                }"
              >
                {{ useEnumeratePicker(afterSalesStatusList, form.aftersales_status) }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="header-right flex" :class="{ '!flex-wrap': isMobile }">
          <!-- 主要按钮区 -->
          <template v-if="form.order_status !== 20">
            <div class="button-group">
              <el-button
                type="success"
                v-if="currentRow.pay_status === 3 && currentRow.order_type !== 2"
                @click="uploadPayment(currentRow, 3)"
                v-hasPermi="['SupplementPaymentOrder']"
              >
                {{ t('order.supplementPayment') }}
              </el-button>

              <el-button
                type="primary"
                v-if="form.order_status === 10 || form.order_status === 21"
                @click="uploadPayment(currentRow, 1)"
              >
                {{ t('order.orderUpload') }}
              </el-button>

              <el-button
                type="warning"
                v-if="form.order_status !== 70"
                @click="uploadPayment(currentRow, 2)"
              >
                {{ t('order.logisticsFeeAdjustment') }}
              </el-button>

              <el-button
                type="primary"
                class="main-button"
                @click="handleCommand(options[0].value)"
              >
                {{ options[0].label }}
              </el-button>

              <el-dropdown
                @command="handleCommand"
                v-if="options.length > 1"
                placement="bottom-end"
              >
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in options.slice(1)"
                      :key="item.value"
                      :command="item.value"
                    >
                      {{ item.label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
                <el-button type="primary" class="triangle-button">
                  <el-icon><ArrowDownBold /></el-icon>
                </el-button>
              </el-dropdown>
            </div>
            <BaseButton
              v-if="form.order_status === 10 && form.total_amount === '0.00'"
              v-hasPermi="['OrderManagementConfirmPayment']"
              type="danger"
              @click="handleSurePayment(form)"
              style="margin-left: 0"
            >
              {{ t('order.confirmPayment') }}
            </BaseButton>
            <BaseButton
              v-if="form.show_entry"
              type="primary"
              @click="handleJump('orderInventoryTypeConversion', form)"
              style="margin-left: 0"
            >
              {{ t('order.inventoryTypeConversion') }}
            </BaseButton>
            <BaseButton
              v-if="(form.pay_status === 3 || form.pay_status === 4) && form.review_node === 1"
              type="primary"
              @click="handleLockInventory(form)"
              style="margin-left: 0"
            >
              {{ t('order.lockInventory') }}
            </BaseButton>
            <BaseButton
              v-if="
                (form.order_status === 10 ||
                  form.order_status === 30 ||
                  form.order_status === 40) &&
                form.order_type != 2 &&
                form.review_node == 0
              "
              v-hasPermi="['OrderManagementEdit']"
              @click="handleJump('edit', form)"
              style="margin-left: 0"
            >
              {{ t('order.edit') }}
            </BaseButton>
            <BaseButton
              v-hasPermi="['OrderManagementDelivery']"
              v-if="
                (form.order_status === 30 || form.order_status === 40) && form.review_node !== 1
              "
              type="primary"
              @click="handleJump('delivery', form)"
              style="margin-left: 0"
            >
              {{ t('order.delivery') }}
            </BaseButton>
            <BaseButton
              v-hasPermi="['OrderManagementPartDelivery']"
              v-if="form.pay_status === 4 && form.review_node !== 1 && !form.aftersales_status"
              type="primary"
              @click="openDeliveryDialog(form)"
              style="margin-left: 0"
            >
              {{ t('order.applyPartialDelivery') }}
            </BaseButton>
            <BaseButton
              v-hasPermi="['OrderManagementCancel']"
              v-if="form.order_status === 10"
              type="info"
              @click="handleCancelOrder(form)"
              style="margin-left: 0"
            >
              {{ t('order.cancelOrder') }}
            </BaseButton>
            <BaseButton
              v-hasPermi="['OrderManagementDelete']"
              v-if="(form.pay_status === 1 && form.order_status === 10) || form.order_status === 70"
              type="danger"
              @click="handleDeleteOrder(form)"
              style="margin-left: 0"
            >
              {{ t('order.deleteOrder') }}
            </BaseButton>
          </template>
          <BaseButton
            v-if="form.order_status === 20"
            type="success"
            @click="handleJump('audit', form)"
            style="margin-left: 0"
          >
            {{ t('order.audit') }}
          </BaseButton>
          <BaseButton
            v-if="form.order_status === 20 && userStore.getUserInfo?.id == form.creator_id"
            type="primary"
            @click="handleJump('auditCancel', form)"
            style="margin-left: 0"
          >
            {{ t('common.cancelExamine') }}
          </BaseButton>
          <BaseButton @click="back" style="margin-left: 0">
            {{ t('action.back') }}
          </BaseButton>
        </div>
      </div>
      <el-divider />
      <div
        class="nav flex flex-start items-center"
        :class="{ '!flex-col !gap-10px !items-start': isMobile }"
      >
        <div class="flex flex-start items-center" @click="checkCustomer">
          <text>{{ t('order.customer') }}：</text>
          <el-link type="primary" class="!text-16px">{{ form.user_name }}</el-link>
        </div>
        <text
          >{{ t('order.signatory') }}：{{ useEnumeratePicker(operatorList, form.signatory) }}</text
        >
        <text>{{ t('order.signing_date') }}：{{ form.signing_date }}</text>
      </div>
      <br />
      <div class="order-detail-wrap mobile-table mobile-card">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane :label="t('order.baseInfo')" name="base_info" />
          <el-tab-pane :label="t('order.team')" name="team" />
          <el-tab-pane :label="t('order.receipt')" name="delivery" />
          <el-tab-pane :label="t('order.logistics')" name="logistics" />
          <el-tab-pane :label="t('order.followList')" name="follow_list" />
          <el-tab-pane :label="t('order.receiptManagement')" name="receipt_management" />
          <el-tab-pane :label="t('order.invoicingHistory')" name="invoicing_history" />
          <el-tab-pane :label="t('order.fileCabinet')" name="file_cabinet" />
          <el-tab-pane :label="t('order.workOrderRecord')" name="work_order_record" />
          <el-tab-pane :label="t('order.relatedProducts')" name="related_products" />
          <el-tab-pane :label="t('order.approvalRecord')" name="approval_record" />
          <el-tab-pane :label="t('order.operateRecord')" name="operate_record" />
        </el-tabs>
        <!-- 动态加载对应的 tab 内容 -->
        <component
          v-if="!isLoading"
          :is="currentTabComponent"
          :key="countKey"
          :current-row="currentRow"
          :operator-options="optionSet"
          @refresh="refresh"
        />
      </div>
    </template>
  </ContentDetailWrap>
  <el-dialog
    v-model="previewVisible"
    :title="t('order.contract')"
    width="80%"
    height="92%"
    :before-close="handleClosePreview"
  >
    <iframe :src="pdfUrl" style="width: 100%; height: 80vh" frameborder="0"></iframe>
  </el-dialog>
  <!--      上传支付凭证弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="refresh" />
  <!--增补费用弹框-->
  <!-- <SupplementPayment ref="SupplementPaymentRef" @refresh="initialize" /> -->
  <!--商品信息发货弹框-->
  <DialogPartShop
    ref="dialogPartShopRef"
    :key="dialogKey"
    :orderInfo="form"
    :operatorOptions="optionSet"
    @refresh="refresh"
  />
</template>

<style lang="less" scoped>
.header-right {
  display: flex;
  align-items: center;
  gap: 10px; /* 增加间距，使按钮不会挤在一起 */
}

.header-left .left {
  flex-direction: column;
  justify-content: space-around;
  margin-right: 10px;
}

.header-left .right .bottom span {
  margin-right: 10px;
}

.nav {
  gap: 50px;
}

.button-group {
  display: flex;
  align-items: center;
  gap: 0; /* 确保按钮组不额外增加间距 */
}

/* 主按钮样式 */
.main-button {
  margin-right: -1px; /* 让按钮无间隙连接 */
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

/* 下拉三角按钮 */
.triangle-button {
  display: flex;
  padding: 0 12px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  align-items: center;
  justify-content: center;
}
</style>
